import { routes } from "@/constants/routes";
import { getGlobalData, setGlobalData } from "@/global_data";
import { back, redirectToWithParams, switchTab } from "@/helper/utils";
import { getPhone, useInfo, wxLogin } from "@/services/entities/all";
import { View, Button } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import "./index.scss";

const InitPage = () => {
  const router = useRouter();
  const { route, action, ...otherParams } = router.params;
  const [showUser, setShowUser] = useState(false);
  const [showPhone, setShowPhone] = useState(false);

  const loginSuccess = () => {
    if (action === "back") {
      back();
      return;
    }
    if (route && routes[route.toUpperCase()]) {
      if (action === "redirect") {
        redirectToWithParams(routes[route.toUpperCase()], otherParams);
      }
    } else {
      switchTab(routes.ROUTES_INDEX);
    }
  };

  const onGetUserInfo = (user) => {
    try {
      const userData = getGlobalData("userInfo");
      useInfo({
        sessionKey: userData.sessionKey,
        encryptedData: user.encryptedData,
        iv: user.iv,
        openId: userData.openId,
        unionId: userData.unionId,
      }).then((userInfo: any) => {
        console.log("userInfo", userInfo);
        setGlobalData("userInfo", { ...userData, userInfo });
        setShowUser(false);
        if (!userInfo.phone) {
          setShowPhone(true);
        } else {
          loginSuccess();
        }
      });
    } finally {
      // switchTab(routes.ROUTES_INDEX);
    }
  };

  const onGetPhoneNumber = (phoneInfo) => {
    console.log(phoneInfo);
    const userData = getGlobalData("userInfo");
    const { detail } = phoneInfo;
    if (detail.encryptedData) {
      getPhone({
        encryptedData: detail.encryptedData,
        iv: detail.iv,
        sessionKey: userData.sessionKey,
        openId: userData.openId,
      }).then(() => {
        loginSuccess();
      });
    }
  };

  const init = async () => {
    const userInfo = getGlobalData("userInfo");
    if (!userInfo.headimgurl) {
      setShowUser(true);
    } else if (!userInfo.phone) {
      setShowPhone(true);
    } else {
      loginSuccess();
    }
  };

  useEffect(() => {
    init();
  }, []);
  return (
    <View className="flex-center bg-page">
      {showUser && (
        <View className="flex-center flex-column">
          <Button
            onClick={() => {
              Taro.getUserProfile({ desc: "用于在我的界面展示用户昵称" }).then(
                (res) => {
                  onGetUserInfo(res);
                }
              );
            }}
          >
            获取用户信息
          </Button>
          <View className="flex-center mt-20 fs-28 lh-36 cl-848484">
            温馨提示，获取用户信息后才能使用小程序
          </View>
        </View>
      )}
      {showPhone && (
        <View className="flex-center flex-column">
          <Button openType="getPhoneNumber" onGetPhoneNumber={onGetPhoneNumber}>
            绑定用户手机号
          </Button>
          <View className="flex-center mt-20 fs-28 lh-36 cl-848484">
            温馨提示，绑定用户手机号后才能使用小程序
          </View>
        </View>
      )}
    </View>
  );
};

export default InitPage;
